<template>
  <div class="vehicle-list-container container">
    <!-- 筛选条件 -->
    <div class="filter-section card">
      <el-form :model="searchForm" label-width="80px" size="small">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="品牌">
              <el-select v-model="searchForm.brandId" placeholder="选择品牌" clearable @change="handleBrandChange">
                <el-option v-for="item in brands" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="车型">
              <el-select v-model="searchForm.seriesId" placeholder="选择车型" clearable>
                <el-option v-for="item in series" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="类型">
              <el-select v-model="searchForm.type" placeholder="车辆类型" clearable>
                <el-option label="经济型" value="1"></el-option>
                <el-option label="舒适型" value="2"></el-option>
                <el-option label="豪华型" value="3"></el-option>
                <el-option label="SUV" value="4"></el-option>
                <el-option label="MPV" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="租期">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="价格">
              <el-select v-model="searchForm.priceRange" placeholder="价格范围" clearable>
                <el-option label="200元以下/天" value="0-200"></el-option>
                <el-option label="200-500元/天" value="200-500"></el-option>
                <el-option label="500-1000元/天" value="500-1000"></el-option>
                <el-option label="1000元以上/天" value="1000-"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="座位数">
              <el-select v-model="searchForm.seats" placeholder="座位数" clearable>
                <el-option label="2座" value="2"></el-option>
                <el-option label="5座" value="5"></el-option>
                <el-option label="7座" value="7"></el-option>
                <el-option label="7座以上" value="8"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="车型/车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <div class="filter-buttons">
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 排序 -->
    <div class="sort-section">
      <el-radio-group v-model="sortOption" size="small" @change="handleSort">
        <el-radio-button label="recommended">推荐</el-radio-button>
        <el-radio-button label="priceAsc">价格低到高</el-radio-button>
        <el-radio-button label="priceDesc">价格高到低</el-radio-button>
        <el-radio-button label="newest">最新上架</el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 车辆列表 -->
    <div class="vehicle-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="vehicle in vehicleList" :key="vehicle.id">
          <el-card shadow="hover" class="vehicle-card" @click.native="viewDetail(vehicle.id)">
            <div class="vehicle-image">
              <img :src="vehicle.imageUrl" :alt="vehicle.name" @error="handleImageError">
              <div v-if="vehicle.tags && vehicle.tags.length" class="vehicle-tags">
                <el-tag v-for="(tag, index) in vehicle.tags" :key="index" size="mini" :type="getTagType(tag)">{{ tag }}</el-tag>
              </div>
            </div>
            <div class="vehicle-info">
              <h3 class="vehicle-title">{{ vehicle.name }}</h3>
              <div class="vehicle-meta">
                <span><i class="el-icon-odometer"></i> {{ vehicle.type }}</span>
                <span><i class="el-icon-user"></i> {{ vehicle.seats }}座</span>
                <span v-if="vehicle.transmission"><i class="el-icon-set-up"></i> {{ vehicle.transmission }}</span>
              </div>
              <div class="vehicle-features" v-if="vehicle.features && vehicle.features.length">
                <el-tag v-for="(feature, index) in vehicle.features.slice(0, 3)" :key="index" size="mini" type="info">{{ feature }}</el-tag>
                <span v-if="vehicle.features.length > 3">等{{ vehicle.features.length }}项</span>
              </div>
              <div class="vehicle-bottom">
                <div class="vehicle-price">
                  <span class="price">¥{{ vehicle.dailyPrice }}</span>
                  <span class="unit">/天</span>
                </div>
                <el-button size="small" type="primary" @click.stop="rentNow(vehicle.id)">立即租车</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 空状态 -->
      <el-empty v-if="vehicleList.length === 0 && !loading" description="暂无符合条件的车辆"></el-empty>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParams.current"
        :page-sizes="[12, 24, 36, 48]"
        :page-size="pageParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { getVehicleList, getVehicleBrands, getVehicleSeries } from '@/api/vehicle'

export default {
  name: 'VehicleList',
  data() {
    return {
      searchForm: {
        brandId: '',
        seriesId: '',
        type: '',
        dateRange: [],
        priceRange: '',
        seats: '',
        keyword: ''
      },
      sortOption: 'recommended',
      pageParams: {
        current: 1,
        size: 12
      },
      vehicleList: [],
      brands: [],
      series: [],
      total: 0,
      loading: false
    }
  },
  created() {
    this.initFromQuery()
    this.fetchBrands()
    this.fetchVehicles()
  },
  methods: {
    initFromQuery() {
      const { query } = this.$route
      
      if (query.brandId) {
        this.searchForm.brandId = query.brandId
        this.fetchSeries(query.brandId)
      }
      
      if (query.seriesId) {
        this.searchForm.seriesId = query.seriesId
      }
      
      if (query.type) {
        this.searchForm.type = query.type
      }
      
      if (query.startDate && query.endDate) {
        this.searchForm.dateRange = [query.startDate, query.endDate]
      }
      
      if (query.minPrice || query.maxPrice) {
        const min = query.minPrice || '0'
        const max = query.maxPrice || ''
        this.searchForm.priceRange = `${min}-${max}`
      }
      
      if (query.seats) {
        this.searchForm.seats = query.seats
      }
      
      if (query.keyword) {
        this.searchForm.keyword = query.keyword
      }
      
      if (query.sort) {
        this.sortOption = query.sort
      }
      
      if (query.page) {
        this.pageParams.current = parseInt(query.page) || 1
      }
      
      if (query.size) {
        this.pageParams.size = parseInt(query.size) || 12
      }
    },
    async fetchBrands() {
      try {
        const res = await getVehicleBrands()
        if (res.code === 0 || res.code === 200) {
          this.brands = res.data || []
        }
      } catch (error) {
        console.error('获取品牌列表失败', error)
      }
    },
    async fetchSeries(brandId) {
      if (!brandId) {
        this.series = []
        return
      }
      
      try {
        const res = await getVehicleSeries(brandId)
        if (res.code === 0 || res.code === 200) {
          this.series = res.data || []
        }
      } catch (error) {
        console.error('获取车系列表失败', error)
      }
    },
    async fetchVehicles() {
      this.loading = true
      
      // 构建查询参数
      const params = {
        ...this.pageParams
      }
      
      if (this.searchForm.brandId) {
        params.brandId = this.searchForm.brandId
      }
      
      if (this.searchForm.seriesId) {
        params.seriesId = this.searchForm.seriesId
      }
      
      if (this.searchForm.type) {
        params.type = this.searchForm.type
      }
      
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        params.startDate = this.searchForm.dateRange[0]
        params.endDate = this.searchForm.dateRange[1]
      }
      
      if (this.searchForm.priceRange) {
        const [min, max] = this.searchForm.priceRange.split('-')
        if (min) params.minPrice = min
        if (max) params.maxPrice = max
      }
      
      if (this.searchForm.seats) {
        params.seats = this.searchForm.seats
      }
      
      if (this.searchForm.keyword) {
        params.keyword = this.searchForm.keyword
      }
      
      if (this.sortOption) {
        params.sort = this.sortOption
      }
      
      try {
        const res = await getVehicleList(params)
        if (res.code === 0 || res.code === 200) {
          // 处理后端返回的数据，映射到前端需要的格式
          this.vehicleList = (res.data.records || []).map(item => ({
            id: item.id,
            name: item.name,
            type: item.typeName,
            seats: item.seats,
            transmission: item.transmissionTypeName,
            dailyPrice: item.dailyRent,
            imageUrl: item.image,
            tags: [
              item.isNew === 1 ? '新车' : null,
              item.brandName
            ].filter(Boolean),
            features: [
              item.transmissionTypeName,
              `${item.seats}座`,
              item.fuelTypeName
            ].filter(Boolean)
          }));
          this.total = res.data.total || 0

          // 如果没有数据，添加一些演示数据
          if (this.vehicleList.length === 0) {
            this.addDemoData()
          }
        }
      } catch (error) {
        console.error('获取车辆列表失败', error)
        this.$message.error('获取车辆列表失败')
        // 添加演示数据
        this.addDemoData()
      } finally {
        this.loading = false
      }
    },
    addDemoData() {
      // 添加演示数据
      this.vehicleList = [
        {
          id: 1,
          name: '奥迪A6L',
          type: '豪华轿车',
          seats: 5,
          transmission: '自动',
          dailyPrice: 399,
          imageUrl: 'https://img2.baidu.com/it/u=306367250,2071323421&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500',
          tags: ['热门', '新车'],
          features: ['GPS导航', '倒车影像', '真皮座椅', '蓝牙音乐']
        },
        {
          id: 2,
          name: '丰田凯美瑞',
          type: '中型轿车',
          seats: 5,
          transmission: '自动',
          dailyPrice: 299,
          imageUrl: 'https://img0.baidu.com/it/u=3581278429,1145643938&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
          tags: ['经济'],
          features: ['倒车影像', '定速巡航', '蓝牙音乐']
        },
        {
          id: 3,
          name: '宝马X5',
          type: 'SUV',
          seats: 5,
          transmission: '自动',
          dailyPrice: 599,
          imageUrl: 'https://img0.baidu.com/it/u=935297709,3165513922&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
          tags: ['豪华', 'SUV'],
          features: ['全景天窗', '电动座椅', '四驱', '自动驻车']
        },
        {
          id: 4,
          name: '别克GL8',
          type: 'MPV',
          seats: 7,
          transmission: '自动',
          dailyPrice: 399,
          imageUrl: 'https://img2.baidu.com/it/u=1006327316,1969001512&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
          tags: ['商务', '舒适'],
          features: ['电动侧滑门', '后排独立空调', '多功能方向盘']
        }
      ]
      this.total = this.vehicleList.length
    },
    handleBrandChange(brandId) {
      this.searchForm.seriesId = ''
      if (brandId) {
        this.fetchSeries(brandId)
      } else {
        this.series = []
      }
    },
    handleSearch() {
      this.pageParams.current = 1
      this.fetchVehicles()
      this.updateRouteQuery()
    },
    resetSearch() {
      this.searchForm = {
        brandId: '',
        seriesId: '',
        type: '',
        dateRange: [],
        priceRange: '',
        seats: '',
        keyword: ''
      }
      this.sortOption = 'recommended'
      this.pageParams.current = 1
      this.series = []
      this.fetchVehicles()
      this.updateRouteQuery()
    },
    handleSort() {
      this.fetchVehicles()
      this.updateRouteQuery()
    },
    handleSizeChange(size) {
      this.pageParams.size = size
      this.fetchVehicles()
      this.updateRouteQuery()
    },
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchVehicles()
      this.updateRouteQuery()
    },
    updateRouteQuery() {
      const query = {}
      
      if (this.searchForm.brandId) {
        query.brandId = this.searchForm.brandId
      }
      
      if (this.searchForm.seriesId) {
        query.seriesId = this.searchForm.seriesId
      }
      
      if (this.searchForm.type) {
        query.type = this.searchForm.type
      }
      
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        query.startDate = this.searchForm.dateRange[0]
        query.endDate = this.searchForm.dateRange[1]
      }
      
      if (this.searchForm.priceRange) {
        const [min, max] = this.searchForm.priceRange.split('-')
        if (min) query.minPrice = min
        if (max) query.maxPrice = max
      }
      
      if (this.searchForm.seats) {
        query.seats = this.searchForm.seats
      }
      
      if (this.searchForm.keyword) {
        query.keyword = this.searchForm.keyword
      }
      
      if (this.sortOption !== 'recommended') {
        query.sort = this.sortOption
      }
      
      if (this.pageParams.current > 1) {
        query.page = this.pageParams.current
      }
      
      if (this.pageParams.size !== 12) {
        query.size = this.pageParams.size
      }
      
      this.$router.replace({ query })
    },
    viewDetail(id) {
      this.$router.push(`/vehicle/detail/${id}`)
    },
    rentNow(id) {
      const query = {}
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        query.startDate = this.searchForm.dateRange[0]
        query.endDate = this.searchForm.dateRange[1]
      }
      
      this.$router.push({
        path: `/order/create`,
        query: { vehicleId: id, ...query }
      })
    },
    getTagType(tag) {
      switch (tag) {
        case '热门':
          return 'danger'
        case '新车':
          return 'success'
        case '豪华':
          return 'warning'
        case 'SUV':
        case '商务':
          return 'info'
        case '经济':
          return 'success'
        case '舒适':
          return 'primary'
        default:
          return ''
      }
    },
    handleImageError(e) {
      // 处理图片加载失败后的逻辑
      console.error('图片加载失败')
      e.target.src = require('@/assets/car-placeholder.png')
    }
  }
}
</script>

<style lang="scss" scoped>
.vehicle-list-container {
  padding: 20px 0;
  
  .filter-section {
    margin-bottom: 20px;
    padding: 20px;
    
    .filter-buttons {
      display: flex;
      justify-content: flex-end;
      margin-top: 29px;
    }
  }
  
  .sort-section {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
  }
  
  .vehicle-list {
    margin-bottom: 30px;
    min-height: 200px;
    
    .vehicle-card {
      margin-bottom: 20px;
      cursor: pointer;
      transition: transform 0.3s, box-shadow 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      }
      
      .vehicle-image {
        position: relative;
        height: 160px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s;
        }
        
        .vehicle-tags {
          position: absolute;
          top: 10px;
          left: 10px;
          
          .el-tag {
            margin-right: 5px;
          }
        }
      }
      
      .vehicle-info {
        padding: 15px 0 5px;
        
        .vehicle-title {
          font-size: 16px;
          margin: 0 0 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .vehicle-meta {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 10px;
          color: #666;
          font-size: 13px;
          
          span {
            margin-right: 15px;
            margin-bottom: 5px;
            
            i {
              margin-right: 5px;
            }
          }
        }
        
        .vehicle-features {
          margin-bottom: 15px;
          
          .el-tag {
            margin-right: 5px;
            margin-bottom: 5px;
          }
          
          span {
            font-size: 12px;
            color: #999;
          }
        }
        
        .vehicle-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .vehicle-price {
            .price {
              font-size: 20px;
              font-weight: bold;
              color: #f56c6c;
            }
            
            .unit {
              font-size: 13px;
              color: #999;
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .vehicle-list-container {
    .filter-section {
      .filter-buttons {
        margin-top: 0;
        margin-bottom: 10px;
      }
    }
    
    .vehicle-list {
      .vehicle-card {
        .vehicle-image {
          height: 140px;
        }
      }
    }
  }
}
</style> 